package com.rabbiter.oes.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbiter.oes.entity.Subject;
import com.rabbiter.oes.result.R;
import com.rabbiter.oes.service.impl.SubjectServiceImpl;
import com.rabbiter.oes.vo.SubjectListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "科目")
@RestController
public class SubjectController {

    @Autowired
    private SubjectServiceImpl subjectService;

    @ApiOperation(value = "分页查询科目信息", notes = "分页查询科目信息", httpMethod = "GET")
    @GetMapping("/subjects/{page}/{size}/{name}")
    public R<IPage<SubjectListVO>> findPage(@PathVariable Integer page, @PathVariable("size") Integer size, @PathVariable("name") String name) {
        Page<SubjectListVO> subjectPage = new Page<>(page, size);
        IPage<SubjectListVO> subjectIPage = subjectService.findPage(subjectPage, name);
        return R.<IPage<SubjectListVO>>ok("分页查询科目信息").data(subjectIPage);
    }

    @ApiOperation(value = "查询全部科目信息", notes = "查询全部科目信息", httpMethod = "GET")
    @GetMapping("/subjectFindAll")
    public R<List<Subject>> findAll() {
        List<Subject> subjects = subjectService.findAll();
        return R.<List<Subject>>ok("分页查询科目信息").data(subjects);
    }

    @ApiOperation(value = "根据id查询科目信息", notes = "根据id查询科目信息", httpMethod = "GET")
    @GetMapping("/subject/{id}")
    public R<Subject> findById(@PathVariable("id") String id) {
        Subject subject = subjectService.findById(id);
        return R.<Subject>ok().data(subject);
    }

    @ApiOperation(value = "根据id删除科目信息", notes = "根据id删除科目信息", httpMethod = "DELETE")
    @DeleteMapping("/subject/{id}")
    public R deleteById(@PathVariable("id") String id) {
        subjectService.deleteById(id);
        return R.ok("删除成功");
    }

    @ApiOperation(value = "修改科目信息", notes = "修改科目信息", httpMethod = "PUT")
    @PutMapping("/subject")
    public R update(@RequestBody Subject subject) {
        String name = subject.getName();
        Long countByName = subjectService.findCountByName(name);
        if (countByName == 0) {
            subjectService.update(subject);
            return R.ok().data(true);
        } else {
            return R.ok("科目已存在！").data(false);
        }
    }

    @ApiOperation(value = "添加科目信息", notes = "添加科目信息", httpMethod = "POST")
    @PostMapping("/subject")
    public R add(@RequestBody Subject subject) {
        String name = subject.getName();
        Long countByName = subjectService.findCountByName(name);
        if (countByName == 0) {
            subjectService.add(subject);
            return R.ok().data(true);
        } else {
            return R.ok("科目已存在！").data(false);
        }
    }


}
